#!/bin/sh

# lock - disallow running two instances of the script
lockfile=/tmp/.rotate.sh.lock
if (set -C; >$lockfile); then
	trap 'rm -f $lockfile' 0 # execute when script finishes
else
	exit; # another instance running
fi 2>/dev/null


# Find the line in "xrandr -q --verbose" output that contains current screen orientation and "strip" out current orientation.
rotation="$(xrandr -q --verbose | grep 'connected' | egrep -o  '\) (normal|left|inverted|right) \(' | egrep -o '(normal|left|inverted|right)')"

# Using current screen orientation proceed to rotate screen and input devices.
# right ma po prawej na górze ekran (punkt 0,0 jest przy czytniku linii papilarnych
# left ma góre tam gdzie jest irda

function set_xfce4_panel {
	# settings
	xfconf-query -c xfce4-panel -p /panels/panel-1/mode -s $1
	xfconf-query -c xfce4-panel -p /panels/panel-1/position -s $2
	xfconf-query -c xfce4-panel -p /panels/panel-2/mode -s $3
	xfconf-query -c xfce4-panel -p /panels/panel-2/length -s $4
	xfconf-query -c xfce4-panel -p /panels/panel-2/position -s $5
	# apply settings by restarting panel (hate kiosk mode)
#	a=$(ps axo command | grep "^xfce4-panel" | head -n1)
#	test ! -z "$a" && killall xfce4-panel || a="xfce4-panel"
#	( exec $a >/dev/null ) &
#	sleep 1
#	xfsettingsd --replace
}

function rotate_normal {
	#wujek wallpaper
	#rm -f /tmp/.X11-unix/wallpaper
	#ln -s ~/wallpaper/land /tmp/.X11-unix/wallpaper
	
	xrandr -o normal
	xsetwacom set stylus rotate none
	xsetwacom set eraser rotate none
	xsetwacom set cursor rotate none
	
	set_xfce4_panel 2 "p=2;x=985;y=384" 0 30 "p=6;x=180;y=16"
	# "p=8;x=445;y=737"
}
function rotate_right {
	#wujek
	#rm -f /tmp/.X11-unix/wallpaper
	#ln -s ~/wallpaper/protrain /tmp/.X11-unix/wallpaper
	
	xrandr -o right
	xsetwacom set stylus rotate cw
	xsetwacom set eraser rotate cw
	xsetwacom set cursor rotate cw
	
	set_xfce4_panel 0 "p=6;x=384;y=38" 1 30 "p=5;x=16;y=240"
	#"p=8;x=445;y=737"
}
function rotate_inverted {
	xrandr -o inverted
	xsetwacom set stylus rotate half
	xsetwacom set eraser rotate half
	xsetwacom set cursor rotate half
	
	set_xfce4_panel 2 "p=6;x=384;y=38" 30 "p=4;x=553;y=748"
}
function rotate_left {
	xrandr -o left
	xsetwacom set stylus rotate ccw
	xsetwacom set eraser rotate ccw
	xsetwacom set cursor rotate ccw
	
	set_xfce4_panel 0 "p=8;x=384;y=981" 30 "p=6;x=384;y=52"
}

case "$rotation" in
normal)
	rotate_right
;;
right)
	rotate_normal
	exit
	rotate_inverted
;;
inverted)
	rotate_left
;;
left)
	rotate_normal
;;
esac


